package com.db;

import java.util.HashMap;
import java.util.Map;
import sender.EmailSenderJava;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

public class MongoDbTools {

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void sendEmailNow() {

		// get sender
		Map _msg_sender = new HashMap();
		_msg_sender.put("_table", Config.SENDER_EMAIL_MESSAGE);
		_msg_sender.put("state", new BasicDBObject("$ne", 0));
		DBObject sender = MongoDb.findOne(_msg_sender);
		if (sender == null) {
			return;
		}
		// get message
		Map _msg = new HashMap();
		_msg.put("_table", Config.NEED_SEND_EMAIL_MESSAGE);
		DBObject message = MongoDb.findOne(_msg);
		if (message == null) {
			return;
		}

		// send message

		Map a = new HashMap();
		a = sender.toMap();
		a.putAll(_msg);
		a.putAll(_msg_sender);
		a.remove("_table");
		try {
			EmailSenderJava.sendMail(a);
			// set sender list use time
			Map _sender = new HashMap();
			_sender.put("_table", Config.SENDER_EMAIL_MESSAGE);
			_sender.put("key", _sender.get("key"));
			DBObject updatesender = new BasicDBObject("$set",
					new BasicDBObject("finallyUseTime", Math.floor(System
							.currentTimeMillis() / Config.SEND_FREQUENCY)));
			MongoDb.update(_sender, updatesender);

			// save to back DB
			BasicDBObject massage = new BasicDBObject();
			massage.putAll(_msg);
			massage.remove("_table");
			massage.put("_table", Config.SEND_OK_EMAIL_MESSAGE);
			MongoDb.insert(massage);
			// remove message
			MongoDb.removeByKey(Config.SEND_OK_EMAIL_MESSAGE,
					(String) _msg.get("key"));

		} catch (Exception e) {
			// set sender to black list
			DBObject aoo = new BasicDBObject("stopTime", Math.floor(System
					.currentTimeMillis() / Config.SENDER_STOP_FREQUENCY));
			aoo.put("state", 0);
			MongoDb.update(new BasicDBObject("key", sender.get("key")),
					new BasicDBObject("$set", aoo));

		}

		// reset sender black list

		BasicDBObject b1 = new BasicDBObject();
		b1.put("stopTime",
				new BasicDBObject("$ne", Math.floor(System.currentTimeMillis()
						/ Config.SENDER_STOP_FREQUENCY)));
		b1.put("state", 0);
		b1.put("_table", Config.SENDER_EMAIL_MESSAGE);
		MongoDb.update(b1, new BasicDBObject("$set", new BasicDBObject("state",
				1)));

	}
}
